#include "transContentPacketMemoryOut.hpp"

int TransContentRecordMemoryOut::sendTo(const EndPoint* target, char* buffer, int bufferLen){
	int _leftBytes;
	int _sendOutBytes;
	int _bufferSize = TransContentMemory::getInstance()->getRecordSize()-50; // 50 bytes header length

	char* _buffer;
	int _bufferIndex;
	int _recordDataLen = 0;

	debug_enter();
	if(buffer == NULL || bufferLen <= 0){
		logd_error("sendTo, parameter buffer error!");
		return E_TRANC_ParamError;
	}

	while(_leftBytes > 0){
		_bufferIndex = TransContentMemory::getInstance()->getBuffer(&_buffer);
		if(_bufferIndex < 0){ 
			logd_error("sendTo, get buffer to store data error!, no buffer avaliable");
			return _bufferIndex;
		}       
		if(_bufferSize > _leftBytes){
			memcpy(_buffer, buffer + _sendBytes, _leftBytes);
			_recordDataLen = _leftBytes;
			_sendBytes += _leftBytes;
			leftBytes = 0;
		}else{  
			memcpy(_buffer, buffer + _sendBytes, _bufferSize);
			leftBytes -= _bufferSize;
			_sendBytes += _bufferSize;
			_recordDataLen = _leftBytes;
		}

		// construct packet
		*(short*(_buffer)) = _recordDataLen + 20;
		_buffer[2] = (char)message_type_out_data_packet; //main code
		*(NodeAddr*(_buffer+3)) = target->addr; //target
		_buffer[11] = (char)SEND_FLAG_USE_PATH_OPTION;
		*(short*(_buffer+12)) = TransContentAssis::SHORTL2N(8 + _recordDataLen);
		_buffer[14] = (char)message_type_out_data_packet; //main code
		_ buffer[15] = (char)message_type_data_packet_sub_dataIn; //sub code
		*(int*(_buffer+16)) = TransContentAssis::INTL2N(target->port); //port
		*(short*(_buffer+20)) = TransContentAssis::SHORTL2N(_recordDataLen);

		/// send to stack
		TransContentDispatcher::getInstance()->sendDataDataToStack(buffer, _recordDataLen + 22);
		TransContentMemory::getInstance()->releaseBuffer(_bufferIndex);
	}
	return E_TRANC_SUCESS;
}

